package com.nebula.tcp.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class NebulaNettyChannelInAdapter extends ChannelInboundHandlerAdapter {

    //换成相对线程安全的ConcurrentHashMap
    public static ConcurrentHashMap<Object, Object> channelMap = new ConcurrentHashMap<>();

    //设备号通道
    public static ConcurrentHashMap<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();



    /**
     * 从客户端收到新的数据时，这个方法会在收到消息时被调用
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        log.info("客户端连接成功：" + clientIp+"  -客户端发送过来的消息：" + msg.toString()  +"-------");

        ctx.writeAndFlush(msg.toString());
    }


    /**
     * 服务端当read超时, 会调用这个方法
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        if (evt instanceof IdleStateEvent) {  // 2
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {//读超时
                String iMei = (String) channelMap.get(ctx);
                ctx.close();//超时时断开连接
            } else if (event.state() == IdleState.WRITER_IDLE) {//写超时

            } else if (event.state() == IdleState.ALL_IDLE) {//全部超时
            }
        }
        super.userEventTriggered(ctx, evt);
    }

}
